<template>
    <div>
        <el-upload
                action="/api/attach/portraitUpload"
                ref="PortraitUpload"
                list-type="picture-card"
                :before-upload="beforeUpload"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-change="handleChange"
                :http-request="handleRequest"
                :auto-upload="false"
                :file-list="fileList"
        >
<!--           :http-request="handleRequest"-->
<!--            :auto-upload="false"-->
<!--                 :headers="{'Content-Type': 'multipart/form-data; charset=utf-8'}"
-->
            <i class="el-icon-plus"></i>
        </el-upload>
<!--            <el-upload-->
<!--                    action="https://jsonplaceholder.typicode.com/posts/"-->
<!--                    list-type="picture-card"-->
<!--                    :on-preview="handlePictureCardPreview"-->
<!--                    :on-remove="handleRemove">-->
<!--                <i class="el-icon-plus"></i>-->
<!--            </el-upload>-->
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
<!--          <img width="100%" src="http://127.0.0.1/Laravel/blog/public/storage/uploads/image/20230309/MHMcgyrL4DJaYOb0X98GO78kK5bbs4lkfBNSmd76.png" alt="">-->
        </el-dialog>
    </div>
</template>

<script>
import {uploadImages} from "@/api/api";
    export default {
        name: "PortraitUpload",
        props:{
          fileList:{
            type:[],
            default() {
              return [];
            }
          }
        },
        data(){
          return {
              dialogImageUrl: '',
              dialogVisible: false,
              // fileList:[],
            attach_id:-1,
          }
        },
        watch:{
          attach_id:{
            handler(newValue,oldValue){
              console.log("监视属性");
              // console.log(newValue,oldValue);
              this.portraitUpload(newValue);
            }
          },
          // ImageUrl:{
          //   // 监听数据发生变化的处理函数
          //   handler(newValue) {
          //     console.log("newValue",newValue);
          //     this.dialogImageUrl = newValue;//将监听到修改的值赋予到dataAttrs中
          //     console.log(this.dialogImageUrl);
          //   },
          //   // 是否开启深度监听，由于我们上面props中是一个Object对象，所以需要开启深度监听功能
          //   deep: true
          // }
        },
        methods:{
            portraitUpload(value){
              this.$emit("attach",this.attach_id);
            },
            handleRequest(file){
              // console.log('file',file)
              // console.log('submit',JSON.stringify(this.fileList))
            //   手动上传
            //   let files = new FormData();
              var files = new FormData();

              // 只有这样才能传递二进制
              files.append('files',file["file"])
              // files.append('name',JSON.stringify(this.fileList))

              // let arr = []
              // files.forEach(item=>{
              //   arr.push(item)
              // })
              // // console.log(arr)
              // console.log("files)",files);
              // console.log("files.get('files')",files.get('files'));

              // 目前没有什么好的解决办法，先这边做把
              uploadImages(files.get('files')).then((res) =>{
                if (res.code === 200){
                  this.attach_id = res.data.attach_id;
                }
              }).catch(error =>{
                // console.error('error',error)
                // alert(error.message || 'Error')
                this.$message.error(error.message || 'Error');
              })
            },
            handleChange(file, fileList){
              //0:其他
              //1:图片的格式 jpg、jpeg、png、gif、bmp
              //2: txt
              //3:word .doc , .docx
              //4:execl *.xls和*.xlsx
              //5:*.pdf

              console.log("fileList",fileList);
              if (fileList.length > 1){
                // this.fileList = [fileList[fileList.length - 1]]
                this.$message({message:"头像只能提交一张(如果有多张则默认选择第一张)", type:"warning",});
                return false;
                // this.fileList['name']  = file['name'];
                // this.fileList['size']  = file['size'];
                // this.fileList['fileSuffix']  = fileSuffix;
              }
                // console.log('file',file['name'],file['size'],fileSuffix);

                // console.log("this.fileList",this.fileList);
                // 配合auto-upload设置为false 才能真正的手动上传
              this.$refs.PortraitUpload.submit();
                // console.log("fileList",fileList);
            },
            handleRemove(file, fileList) {
                //删除图片
                // console.log("file",file);
                // 当删除到最后一张的时候就可以上传了
                // console.log("fileList", fileList);
              if (fileList.length === 1){
                this.$refs.PortraitUpload.submit();
              }
                // if (fileList.length >=1){
                //   // this.fileList['name']  = fileList['0']['name'] !== '' ? fileList['0']['name'] : "";
                //   // this.fileList['size']  = fileList['0']['size'] !== '' ? fileList['0']['size']  :"";
                //   // this.fileList['fileSuffix']  = this.fileList['name'].substring(this.fileList['name'].lastIndexOf(".") + 1);
                // }
                // console.log(this.fileList);
            },
            handlePictureCardPreview(file) {
              console.log("12345678",file);
                //放大图片
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            beforeUpload(file){
              const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
              // console.log(fileSuffix);
              const whiteList = ["jpg", "jpeg", "png", "gif", "bmp"];
              // const whiteList = ["pdf", "doc", "docx", "xls", "xlsx"];
              if (whiteList.indexOf(fileSuffix) === -1) {
                this.$message({message:"上传文件只能是图片格式", type:"error",});
                return false;
              }
              const isLt2M = file.size / 1024 / 1024 < 2;
              if (!isLt2M) {
                this.$message({message:"上传文件大小不能超过 2MB", type:"error",});
                return false;
              }
            }
        },

    }
</script>

<style scoped>

</style>